package com.remote.server.handle;


import com.remote.common.RemoteFactory;
import com.remote.common.model.Request;
import com.remote.common.model.Response;
import com.remote.common.model.ServerClientInfo;
import com.remote.common.util.Utils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.StringUtil;

import static com.remote.common.constant.Constants.CLIENT_INFO;
import static com.remote.common.constant.MessageConstants.*;

/**
 * 事件发送处理
 */
public class FireCommandHandler extends BaseServerHandler {

    public FireCommandHandler(RemoteFactory remoteFactory) {
        super(remoteFactory);
    }

    @Override
    protected void handleO(ChannelHandlerContext ctx, Request inbound) {
        if (StringUtil.isNullOrEmpty(inbound.getTargetClientId())) {
            error(inbound, WRONG_CLIENT_ID);
            Utils.sendError(ctx.channel(), inbound, WRONG_CLIENT_ID);
            return;
        }
        final ServerClientInfo sourceInfo = ctx.channel().attr(CLIENT_INFO).get();
        if (sourceInfo == null) {
            error(inbound, MASTER_CONNECTION_LOST);
            Utils.sendError(ctx.channel(), inbound, MASTER_CONNECTION_LOST);
            return;
        }
        ChannelHandlerContext puppetContext = sourceInfo.puppetContexts().get(inbound.getTargetClientId());
        if (puppetContext == null || !puppetContext.channel().isOpen()) {
            error(inbound, PUPPET_CONNECTION_LOST);
            Utils.sendError(ctx.channel(), inbound, PUPPET_CONNECTION_LOST);
            return;
        }
        //发送数据
        Response response = Utils.buildResponse(inbound, inbound.getCommand(), inbound.getValue());
        puppetContext.writeAndFlush(response);
    }
}
